package com.jerry.frame.rpc.common;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by zjh on 2017/8/8.
 */
public class NamedThreadFactory implements ThreadFactory {
    private final AtomicInteger id = new AtomicInteger();
    //线程名称
    private final String name;
    //是否守护进程
    private final Boolean daemon;
    //优先级
    private final Integer priority;
    //线程组
    private final ThreadGroup group;

    public NamedThreadFactory(String name) {

        this(name, false, Thread.NORM_PRIORITY);
    }

    public NamedThreadFactory(String name, boolean daemon, int priority) {
        this.name = name + " #";
        this.daemon = daemon;
        this.priority = priority;
        SecurityManager s = System.getSecurityManager();
        group = (s == null) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup();
    }

    public NamedThreadFactory(String name, boolean daemon, int priority, ThreadGroup group) {
        this.name = name;
        this.daemon = daemon;
        this.priority = priority;
        this.group = group;
    }

    public NamedThreadFactory(String name, boolean daemon) {
        this(name, daemon, Thread.NORM_PRIORITY);
    }

    public Thread newThread(Runnable r) {
        String name = this.name + id.getAndIncrement();
        Thread t = new Thread(group,r,name);
        if(this.daemon!=null){
            t.setDaemon(this.daemon);
        }
        if(this.priority!=null){
            t.setPriority(this.priority);
        }
        return t;
    }
}
